package com.lm.delayqueue.example;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

public class OrderDelayQueueManager {
    private final DelayQueue<OrderTask> delayQueue = new DelayQueue<>();

    public void addOrder(String orderId, long delaySeconds) {
        OrderTask task = new OrderTask(orderId, delaySeconds, TimeUnit.SECONDS);
        delayQueue.offer(task);
        System.out.println("订单提交：" + orderId + "，将在 " + delaySeconds + " 秒后超时处理。");
    }

    public void start() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    OrderTask task = delayQueue.take(); // 阻塞直到到期
                    System.out.println("订单超时取消处理：" + task.getOrderId());
                } catch (InterruptedException e) {
                    break;
                }
            }
        }, "delay-queue-thread");

        thread.setDaemon(true);
        thread.start();
    }
}